import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Space,
  Select,
  message,
} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { useCommon } from '@/hooks/common';

const typeMap: any = { 1: '店铺用户', 2: '设计师', 3: '分销商', 4: '供应商' };
const typeOptions = Object.keys(typeMap).map((key) => {
  return { label: typeMap[key], value: key };
});

export default function ListPage() {
  const uri = 'member';
  const cateName = '会员管理';
  const {
    data = {},
    ModalPros,
    searchForm,
    onSearchFormReset,
    onEdit,
    onSearch,
    handleChange,
  } = useCommon({ loginName: '', id: '', userName: '', userType: '' }, uri, {
    loginName: '',
    id: 0,
    userName: '',
    userType: '',
    phoneNumber: '',
  });

  const levelMap: any = {};

  const [levels, setLevels] = useState([]);
  const [showBind, setShowBind] = useState(false);
  const [bindId, setBindId] = useState('');

  useEffect(() => {
    commonService.getListApi('member-level', { pageNo: 1, pageSize: 100 }).then(({ list }) => {
      setLevels(list.map((item: any) => {
        levelMap[item.id] = item.levelName;
        return {label: item.levelName, value: item.id};
      }));
    });
  }, []);

  const onBind = (id: string) => {
    setBindId(id);
    setShowBind(true);
  };

  const columns: ColumnsType<any> = [
    { title: '会员ID', dataIndex: 'id', align: 'center', width: 60 },
    { title: '姓名', dataIndex: 'userName', align: 'center', width: 60 },
    { title: '手机号', dataIndex: 'phoneNumber', align: 'center', width: 140 },
    {
      title: '会员类型',
      dataIndex: 'userType',
      align: 'center',
      width: 120,
      render: (userType) => <div>{typeMap[userType]}</div>,
    },
    {title: '会员等级', dataIndex: 'levelName', align: 'center', width: 60},
    { title: '注册时间', dataIndex: 'createTime', align: 'center', width: 120 },
    // { title: '考核开始时间', dataIndex: 'des', align: 'center', width: 120 },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 80,
      render: (_, record) => (
        <div className="flex flex-col gap-[10px] w-full justify-center text-gray">
          <Button onClick={() => onEdit(record)}>编辑身份</Button>
          <Button onClick={() => onBind(record.id)}>绑定推广人</Button>
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="登陆账号" name="loginName" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="姓名" name="userName" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="用户ID" name="id" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="手机" name="phoneNumber" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="会员类型" name="userType" className="!mb-0">
                <Select options={typeOptions} />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title={cateName}
        extra={
          <div className="flex flex-row gap-[10px]">
            {/* <Button
              type="primary"
              onClick={() =>
                onCreate({ parentId: query.parentId, level: query.parentId === 0 ? 1 : 2 })
              }
            >
              新增
            </Button> */}
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      <CommonModal {...ModalPros} levels={levels} />
      <BindModal onOk={() => setShowBind(false)} onCancel={() => setShowBind(false)} show={showBind} userId={bindId}  />
    </Space>
  );
}

function BindModal({ show, onOk, onCancel, userId }: any) {
  const [form] = Form.useForm();

  const handleOk = () => {
    const params = {...form.getFieldsValue(), userId };
    commonService.getCustomApi('/admin/member/bindT', params).then(() => {
      message.success('绑定成功');
      onOk();
    });
  };

  return (
    <Modal
      title="绑定用户"
      open={show}
      onOk={handleOk}
      onCancel={onCancel}
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        layout="horizontal"
      >
        <Form.Item<any> label="邀请码" name="invitationCode" required>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}

function CommonModal({ title, show, formValue, onOk, onCancel, levels }: any) {
  const [form] = Form.useForm();
  const userType = Form.useWatch('userType', form);

  const handleOk = () => {
    const params = { ...formValue, ...form.getFieldsValue() };
    if (params.inspectionTime) {
      params.inspectionTime = dayjs(params.inspectionTime).format('YYYY-MM-DD hh:mm:ss');
    }
    params.userType = Number(params.userType);
    onOk(params);
  };

  useEffect(() => {
    form.setFieldsValue({ ...formValue, userType: String(formValue.userType), inspectionTime: dayjs(formValue.inspectionTime) });
  }, [formValue, form]);
  return (
    <Modal
      title={title}
      open={show}
      onOk={() => handleOk()}
      onCancel={onCancel}
    >
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        layout="horizontal"
      >
        <Form.Item<any> label="会员昵称" name="userName" required>
          <Input disabled />
        </Form.Item>
        <Form.Item<any> label="手机号" name="phoneNumber" required>
          <InputNumber disabled style={{ width: '200px' }} />
        </Form.Item>
        <Form.Item<any> label="类型" name="userType" required>
          <Select options={typeOptions} />
        </Form.Item>
        {(Number(userType) > 2) ? <><Form.Item<any> label="会员等级" name="userLevel" required>
          <Select options={levels} disabled={formValue.useType < 3} />
        </Form.Item>
        {/* <Form.Item<any> label="考核开始时间" name="inspectionTime" required>
          <DatePicker format="YYYY-MM-DD hh:mm:ss" />
        </Form.Item> */}
        </> : ''}
      </Form>
    </Modal>
  );
}
